﻿using Face8280WebSocketServer.Interface;
using Face8280WebSocketServer.Model.People;
using Face8280WebSocketServer.Utility;
using Face8280WebSocketServer.Utility.ExpressionExtend;
using Face8280WebSocketServer.Utility.FilterAttribute;
using Face8280WebSocketServer.Utility.Model;
using Face8280WebSocketServer.Controllers.User;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
using Face8280WebSocketServer.DTO;

namespace Face8280WebSocketServer.Controllers.People
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class PeopleController : ControllerBase
    {

        private readonly ILogger<PeopleController> _logger;
        private IMyMemoryCache _Cache;
        private IPeopleService _PeopleDB;

        public PeopleController(ILogger<PeopleController> logger,
            IPeopleService peopledb, IMyMemoryCache mycache)
        {
            _logger = logger;
            _PeopleDB = peopledb;
            _Cache = mycache;
        }


        /// <summary>
        /// 获取已安装的人员表格
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetPeopleTable")]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult GetPeopleTable([FromForm] PeopleQueryParameter par)
        {

            List<Expression<Func<FacePeople, bool>>> oWheres = new();
            if (par.EmployeeID > 0) oWheres.Add(x => x.EmployeeID.Equals(par.EmployeeID));
            if (par.EmployeeIC > 0) oWheres.Add(x => x.EmployeeIC.Equals(par.EmployeeIC));
            if (par.EmployeePhoto > 0)
            {
                if (par.EmployeePhoto == 1)
                    oWheres.Add(x => x.PhotoLen > 0);
                else
                    oWheres.Add(x => x.PhotoLen == 0);
            }

            if (!string.IsNullOrWhiteSpace(par.EmployeeName)) oWheres.Add(x => x.EmployeeName.Contains(par.EmployeeName));
            if (!string.IsNullOrWhiteSpace(par.EmployeeJob)) oWheres.Add(x => x.EmployeeJob.Contains(par.EmployeeJob));
            if (!string.IsNullOrWhiteSpace(par.EmployeePhone)) oWheres.Add(x => x.EmployeePhone.Contains(par.EmployeePhone));
            //_logger.LogInformation("获取人员列表");
            var peoples = _PeopleDB.QueryPage(
                x => new
                {
                    x.ID,
                    x.EmployeeID,
                    x.EmployeeName,
                    x.EmployeePassword,
                    x.EmployeeIC,
                    x.PhotoLen,
                    x.EmployeePhoto,
                    x.EmployeeJob,
                    x.EmployeePhone
                },
                oWheres, par.pageSize, par.pageIndex,
                x => x.EmployeeID,
                par.isAsc);

            return new JsonResult(new JsonResultModel(peoples));
        }

        [HttpPost]
        [Route("GetPeopleTableMini")]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult GetPeopleTableMini([FromForm] PeopleQueryParameter par)
        {

            List<Expression<Func<FacePeople, bool>>> oWheres = new();
            if (par.EmployeeID > 0) oWheres.Add(x => x.EmployeeID.Equals(par.EmployeeID));
            if (par.EmployeeIC > 0) oWheres.Add(x => x.EmployeeIC.Equals(par.EmployeeIC));
            if (par.EmployeePhoto > 0)
            {
                if (par.EmployeePhoto == 1)
                    oWheres.Add(x => x.PhotoLen > 0);
                else
                    oWheres.Add(x => x.PhotoLen == 0);
            }

            if (!string.IsNullOrWhiteSpace(par.EmployeeName)) oWheres.Add(x => x.EmployeeName.Contains(par.EmployeeName));
            if (!string.IsNullOrWhiteSpace(par.EmployeeJob)) oWheres.Add(x => x.EmployeeJob.Contains(par.EmployeeJob));
            if (!string.IsNullOrWhiteSpace(par.EmployeePhone)) oWheres.Add(x => x.EmployeePhone.Contains(par.EmployeePhone));
            //_logger.LogInformation("获取人员列表");
            var peoples = _PeopleDB.QueryPage(
                x => new
                {
                    x.ID,
                    x.EmployeeID,
                    x.EmployeeName,
                    x.EmployeePassword,
                    x.EmployeeIC,
                    x.EmployeePhoto
                },
                oWheres, par.pageSize, par.pageIndex,
                x => x.EmployeeID,
                par.isAsc);

            return new JsonResult(new JsonResultModel(peoples));
        }



        [HttpPost]
        [Route("GetPeopleIDList")]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult GetPeopleIDList([FromForm] BasePageParameter par)
        {


            //_logger.LogInformation("获取人员列表");
            var peoples = _PeopleDB.Query<FacePeople>(null);
            var q = from p in peoples
                    orderby p.EmployeeID
                    select p.ID
                    ;

            PageResult<int> result = new PageResult<int>()
            {
                DataList = q.Skip((par.pageIndex - 1) * par.pageSize).Take(par.pageSize).ToList(),
                PageIndex = par.pageIndex,
                PageSize = par.pageSize,
                TotalCount = q.Count()
            };

            return new JsonResult(new JsonResultModel(result));
        }


        /// <summary>
        /// 添加人员信息
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddAndFile")]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult AddAndFile([FromForm] string postdata, [FromForm] IFormCollection files)
        {
            var oUpdatePar = JsonConvert.DeserializeObject<PeopleAddParameter>(postdata);
            IActionResult errResult = null;
            if (!VerifyActionFilterAttribute.VerifyEntity(typeof(PeopleAddParameter), oUpdatePar, r => errResult = r)) return errResult;

            return Add(oUpdatePar, files);
        }

        /// <summary>
        /// 添加人员信息
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Add")]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult Add([FromForm] PeopleAddParameter par, [FromForm] IFormCollection files)
        {
            var people = new FacePeople();

            par.CopyTo(people);

            people.EmployeePhotoWay = string.Empty;
            people.PhotoLen = 0;
            people.EmployeePhoto = string.Empty;

            var result = _PeopleDB.AddNew(people, p => CheckPeopleImage(p, files, par.EmployeePhotoWay));
            if (result.result)
            {
                result.content = people.ID;
                //_logger.LogInformation($"添加人员 ID:{people.ID} 编号：{people.EmployeeID} 姓名：{people.EmployeeName}");
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 更新人员信息
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateAndFile")]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult UpdateAndFile([FromForm] string postdata, [FromForm] IFormCollection files)
        {
            var oUpdatePar = JsonConvert.DeserializeObject<PeopleUpdateParameter>(postdata);
            IActionResult errResult = null;
            if (!VerifyActionFilterAttribute.VerifyEntity(typeof(PeopleUpdateParameter), oUpdatePar, r => errResult = r)) return errResult;

            return Update(oUpdatePar, files);
        }

        /// <summary>
        /// 检查照片
        /// </summary>
        /// <param name="p"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        private JsonResultModel CheckPeopleImage(FacePeople people, IFormCollection files, string EmployeePhotoWay)
        {
            string sPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "People");
            if (!Directory.Exists(sPath))
            {
                Directory.CreateDirectory(sPath);
            }

            string sFileName = $"{people.EmployeeID}.jpg";
            if (EmployeePhotoWay.Equals("path"))
            {
                if (files.Files.Count == 1)
                {
                    string sFile = Path.Combine(sPath, sFileName);
                    try
                    {
                        if (System.IO.File.Exists(sFile)) System.IO.File.Delete(sFile);

                        var uploadFile = files.Files[0];
                        if (uploadFile.Length > 0)
                        {
                            if (uploadFile.Length > 20971520)//20*1024KB=20M
                            {
                                return new JsonResultModel(202, "人员照片太大，请先压缩照片！");
                            }
                            people.EmployeePhotoWay = "path";
                            people.PhotoLen = (int)uploadFile.Length;
                            string crc;
                            using (var stream = new MemoryStream(people.PhotoLen))
                            {
                                uploadFile.CopyTo(stream);
                                byte[] bImg = stream.ToArray();
                                bImg = FaceImageUtil.ConvertImage(bImg);

                                crc = CRC32_C.CalculateDigest(bImg, 0, (uint)bImg.Length).ToString("x");
                                System.IO.File.WriteAllBytes(sFile, bImg);
                            }


                            people.EmployeePhoto = $"/People/{sFileName}?crc32={crc}";
                        }
                    }
                    catch (Exception)
                    {

                        throw;
                    }

                }
                else
                {
                    return new JsonResultModel(203, "人员照片参数错误！");
                }
            }
            else if (EmployeePhotoWay.Equals("base"))
            {
                return new JsonResultModel(204, "人员照片格式错误，请使用文件上传方式");
            }
            else if (EmployeePhotoWay.Equals("Delete"))
            {
                //删除照片
                if (people.PhotoLen > 0)
                {
                    people.EmployeePhotoWay = string.Empty;
                    sFileName = people.EmployeePhoto;
                    people.EmployeePhoto = string.Empty;
                    people.PhotoLen = 0;
                    if (sFileName.StartsWith("/People"))
                    {
                        var sFile = GetImageFileName(sFileName);

                        if (System.IO.File.Exists(sFile))
                            System.IO.File.Delete(sFile);
                    }

                }
            }
            else if (EmployeePhotoWay.Equals("NULL"))
            {

            }
            else
            {
                //没有照片
                people.EmployeePhotoWay = string.Empty;
                people.PhotoLen = 0;
                people.EmployeePhoto = string.Empty;
            }
            return new JsonResultModel();
        }

        /// <summary>
        /// 更新人员信息
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Update")]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public IActionResult Update([FromForm] PeopleUpdateParameter par, [FromForm] IFormCollection files)
        {
            var people = _PeopleDB.Find<FacePeople>(par.ID);
            if (people == null) return new JsonResult(new JsonResultModel(200, "人员不存在"));
            string sOldEmployeePhotoWay = people.EmployeePhotoWay;
            //更新人员权限
            par.CopyTo(people);
            people.EmployeePhotoWay = sOldEmployeePhotoWay;

            //检查图片
            var result = CheckPeopleImage(people, files, par.EmployeePhotoWay);
            if (!result.result)
            {
                return new JsonResult(result);
            }
            else
            {
                result = _PeopleDB.UpdatePeople(people);
                if (!result.result)
                {
                    return new JsonResult(result);
                }
                else
                {
                    //_logger.LogInformation($"更新人员：ID:{people.ID} 编号：{people.EmployeeID} 姓名:{people.EmployeeName}");
                    result.content = new { par.ID, people.PhotoLen, people.EmployeePhoto, people.EmployeePhotoWay };
                }
            }
            return new JsonResult(new JsonResultModel(result));
        }


        /// <summary>
        /// 从URL 连接中获取文件名，去掉末尾的?crc
        /// </summary>
        /// <param name="sPath"></param>
        /// <param name="sFileName"></param>
        /// <returns></returns>
        private string GetImageFileName(string sURL)
        {
            string sPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");


            var iIndex = sURL.LastIndexOf("?");
            if (iIndex > 0)
            {
                sURL = sURL.Substring(0, iIndex);
            }
            string[] sURLSegments = sURL.Split("/");
            string sFile = sPath;
            foreach (var sSegment in sURLSegments)
            {
                sFile = Path.Combine(sFile, sSegment);
            }
            return sFile;
        }

        /// <summary>
        /// 删除人员
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Delete")]
        [TypeFilter(typeof(VerifyActionFilterAttribute))]
        public async Task<IActionResult> Delete([FromForm] PeopleDeleteParameter par)
        {


            if (par.PeopleIDs == null)
            {
                return new JsonResult(new JsonResultModel(1, "未选择需要删除的人员"));
            }
            if (par.PeopleIDs.Count == 0)
            {
                return new JsonResult(new JsonResultModel(1, "未选择需要删除的人员"));
            }

            HashSet<int> peopleIDLists = new HashSet<int>(par.PeopleIDs);
            var peoplesDB = _PeopleDB.Query<FacePeople>(x => peopleIDLists.Contains(x.ID))
                .Select(x => new FacePeople
                {
                    ID = x.ID,
                    EmployeeName = x.EmployeeName,
                    EmployeeID = x.EmployeeID,
                    EmployeeJob = x.EmployeeJob,
                    EmployeeIC = x.EmployeeIC,
                    EmployeePhoto = x.EmployeePhoto
                });

            await Task.Run(() =>
            {
                string sPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "People");
                if (!Directory.Exists(sPath))
                {
                    Directory.CreateDirectory(sPath);
                }
                foreach (var p in peoplesDB)
                {
                    _PeopleDB.AddUserLog("人员管理",
                $"删除人员：{p.EmployeeName}({p.EmployeeID}),职务：{p.EmployeeJob},卡号：{p.EmployeeIC},照片地址：{p.EmployeePhoto}",
                string.Empty, $"{p.EmployeeName}({p.EmployeeID})");


                    if (!string.IsNullOrWhiteSpace(p.EmployeePhoto))
                    {
                        var sFileName = GetImageFileName(p.EmployeePhoto);
                        if (System.IO.File.Exists(sFileName))
                        {
                            try
                            {
                                System.IO.File.Delete(sFileName);
                            }
                            catch (Exception ex)
                            {

                                _logger.LogError($" Delete 删除文件时发生错误：{sFileName}  {ex.Message} ");
                            }

                        }
                    }

                }
            });

            _PeopleDB.Delete(peoplesDB.AsEnumerable());
            //_logger.LogInformation($"删除人员列表 ID列表：{string.Join(",", par.PeopleIDs.Select(id => id.ToString()))}");

            return new JsonResult(new JsonResultModel(par));
        }


        /// <summary>
        /// 获取人员详情
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetPeopleDetail/{ID}")]
        public IActionResult GetPeopleDetail(int ID)
        {
            var people = _PeopleDB.Find<FacePeople>(ID);
            if (people == null) return new JsonResult(new JsonResultModel(10, "人员不存在"));



            return new JsonResult(new JsonResultModel(people));
        }

        /// <summary>
        /// 根据Excel导入人员
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("InputPeopleByExcel")]
        public  IActionResult InputPeopleByExcel([FromForm] IFormCollection files)
        {
            if (files.Files.Count != 1)
            {
                return new JsonResult(new JsonResultModel(1, "仅支持上传一个文件"));
            }
            var xlsFile = files.Files[0];
            var sFileName = xlsFile.FileName;
            var fileExt = Path.GetExtension(sFileName).ToLower();
            List<FacePeople> peoples = new List<FacePeople>();
            using (var xlsStream = xlsFile.OpenReadStream())
            {
                IWorkbook book = null;
                try
                {
                    switch (fileExt)
                    {
                        case ".xlsx":
                            book = new XSSFWorkbook(xlsStream);
                            break;
                        case ".xls":
                            book = new HSSFWorkbook(xlsStream);
                            break;
                        default:
                            return new JsonResult(new JsonResultModel(2, "不支持此文件"));
                    }
                    if (book.NumberOfSheets == 0)
                    {
                        return new JsonResult(new JsonResultModel(4, "Excel中没有表格"));
                    }
                }
                catch (Exception ex)
                {

                    return new JsonResult(new JsonResultModel(3, "Excel 格式解析失败，请重新编辑文件! " + Environment.NewLine + ex.Message));
                }
                //Excel 格式检查


                try
                {
                    #region 标题检查
                    var sColTitle = "人员编号,人员姓名,密码,卡号,职务,联系方式,身份证信息,地址信息,照片URL,人脸识别阈值".Split(",");
                    var sheet = book.GetSheetAt(0);
                    var oTitelRow = sheet.GetRow(sheet.FirstRowNum);
                    if (oTitelRow == null)
                    {
                        return new JsonResult(new JsonResultModel(5, "Excel 未包含标题 "));
                    }
                    var minCol = oTitelRow.FirstCellNum;
                    for (int i = 0; i < sColTitle.Length; i++)
                    {
                        var sTitle = GetExcelCellValue(oTitelRow.GetCell(i));
                        if (sTitle != sColTitle[i])
                        {
                            return new JsonResult(new JsonResultModel(6, "Excel 标题检查不通过! "));
                        }
                    }

                    for (int i = 0; i < sColTitle.Length; i++)
                    {
                        var sTitle = GetExcelCellValue(oTitelRow.GetCell(i));
                        if (sTitle != sColTitle[i])
                        {
                            return new JsonResult(new JsonResultModel(6, "Excel 标题检查不通过! "));
                        }
                    }
                    #endregion


                    var iMaxRow = sheet.LastRowNum;
                    var iRow = sheet.FirstRowNum + 1;

                    do
                    {
                        if (iRow > iMaxRow)
                        {
                            break;
                        }
                        var oDataRow = sheet.GetRow(iRow);
                        iRow++;




                        string sValue = GetExcelCellValue(oDataRow.GetCell(0));//人员编号
                        if (string.IsNullOrWhiteSpace(sValue))
                            continue;
                        long lValue;
                        if (!long.TryParse(sValue, out lValue))
                        {
                            continue;
                        }
                        FacePeople people = new FacePeople();
                        people.EmployeeID = lValue;
                        people.EmployeeName = GetExcelCellValue(oDataRow.GetCell(1));//人员姓名
                        people.EmployeePassword = GetExcelCellValue(oDataRow.GetCell(2));//密码

                        //卡号
                        sValue = GetExcelCellValue(oDataRow.GetCell(3));
                        if (long.TryParse(sValue, out lValue))
                        {
                            people.EmployeeIC = lValue;
                        }
                        people.EmployeeJob = GetExcelCellValue(oDataRow.GetCell(4));//职务
                        people.EmployeePhone = GetExcelCellValue(oDataRow.GetCell(5));//联系方式
                        people.EmployeeIdentity = GetExcelCellValue(oDataRow.GetCell(6));//身份证信息
                        people.EmployeeAddress = GetExcelCellValue(oDataRow.GetCell(7));//地址信息
                        people.EmployeePhotoWay = "path";
                        people.EmployeePhoto = GetExcelCellValue(oDataRow.GetCell(8));//照片URL




                        //人脸识别阈值
                        sValue = GetExcelCellValue(oDataRow.GetCell(9));
                        if (long.TryParse(sValue, out lValue))
                        {
                            people.EmployeeShold = lValue;
                        }

                        peoples.Add(people);

                    } while (true);



                }
                catch (Exception)
                {

                    throw;
                }

                if (peoples.Count > 0)
                {
                    #region 验证照片合法性
                    /*
                    List<Task> URLCheckTasks = new List<Task>();
                    int iPeoples = peoples.Count;
                    if (iPeoples < 100)
                    {
                        URLCheckTasks.Add(CheckPeopleURLProgress("Task0", peoples));
                    }
                    else
                    {
                        int iTaskMax = 10;
                        int iBegin = 0;
                        int iChunkCount = iPeoples / iTaskMax;
                        SubList<FacePeople> sub;
                        for (int i = 0; i < iTaskMax; i++)
                        {
                            if (i == iTaskMax - 1)
                            {
                                iChunkCount = iPeoples - iBegin;
                            }
                            sub = new SubList<FacePeople>(peoples, iBegin, iChunkCount);

                            string sTaskName = $"Task{i}";
                            _logger.LogInformation($"{sTaskName} 分组范围：{iBegin} - {iBegin + iChunkCount - 1} 总数： {iChunkCount}");
                            iBegin += iChunkCount;
                            
                            URLCheckTasks.Add(Task.Run(() => CheckPeopleURLProgress($"{sTaskName}", sub)));
                        }

                    }
                    await Task.WhenAll(URLCheckTasks.ToArray());
                    */
                    #endregion
                    //开始导入到数据库
                    _PeopleDB.InputPeople(peoples);
                }

            }

            return new JsonResult(new JsonResultModel());
        }

        private async Task MultiWrokProgress<T>(List<T> sources, Func<string, IEnumerable<T>, Task> WrokProgress)
        {
            List<Task> URLCheckTasks = new List<Task>();
            int iListCount = sources.Count;
            if (iListCount < 100)
            {
                URLCheckTasks.Add(WrokProgress("Task0", sources));
            }
            else
            {
                int iTaskMax = 10;
                int iBegin = 0;
                int iChunkCount = iListCount / iTaskMax;
                SubList<T> sub;
                for (int i = 0; i < iTaskMax; i++)
                {
                    if (i == iTaskMax - 1)
                    {
                        iChunkCount = iListCount - iBegin;
                    }
                    sub = new SubList<T>(sources, iBegin, iChunkCount);

                    string sTaskName = $"Task{i}";
                    _logger.LogInformation($"{sTaskName} 分组范围：{iBegin} - {iBegin + iChunkCount - 1} 总数： {iChunkCount}");
                    iBegin += iChunkCount;

                    URLCheckTasks.Add(WrokProgress($"{sTaskName}", sub));
                }

            }
            await Task.WhenAll(URLCheckTasks.ToArray());
        }

        private async Task CheckPeopleURLProgress(string sTaskName, IEnumerable<FacePeople> peoples)
        {
            IHttpClientFactory clientFactory = this.HttpContext.RequestServices.GetService(typeof(IHttpClientFactory)) as IHttpClientFactory;
            HttpClient httpClient = clientFactory.CreateClient();
            Stopwatch wch = new Stopwatch();
            wch.Start();
            string name = $"{sTaskName} Thread-{Thread.CurrentThread.ManagedThreadId} ";
            int lMax = peoples.Count();
            int lCount = 0;
            int iStep = 0;
            _logger.LogInformation($"{name}  准备处理 {lMax} 个 URL地址请求");
            foreach (var people in peoples)
            {
                //检查这个URL地址
                try
                {
                    //wch.Restart();
                    var request = new HttpRequestMessage(HttpMethod.Head, people.EmployeePhoto);
                    var response = await httpClient.SendAsync(request);
                    if (response.IsSuccessStatusCode)
                    {
                        var headers = response.Content.Headers;
                        if ("image/jpeg".Equals(headers.ContentType.MediaType))
                        {

                            people.PhotoLen = (int)(headers.ContentLength ?? 0);
                            if (response.Headers.Contains("x-oss-hash-crc64ecma"))
                            {
                                var crc64 = response.Headers.GetValues("x-oss-hash-crc64ecma").First();
                                people.EmployeePhoto = people.EmployeePhoto + "?crc64=" + crc64;
                            }
                            else
                            {
                                if (response.Headers.Contains("ETag"))
                                {
                                    var ETag = response.Headers.GetValues("ETag").First();
                                    people.EmployeePhoto = people.EmployeePhoto + "?ETag=" + ETag;
                                }

                            }



                        }
                        else
                        {//不支持的图片格式
                            //_logger.LogError($"{people.EmployeePhoto} 图片格式不支持：{headers.ContentType.MediaType}");
                            people.EmployeePhotoWay = string.Empty;
                            people.EmployeePhoto = string.Empty;
                            people.PhotoLen = 0;
                        }

                    }
                    else
                    {
                        _logger.LogError($"{name} {people.EmployeePhoto} URL地址请求错误 {response.StatusCode} {response.ReasonPhrase}");
                        people.EmployeePhotoWay = string.Empty;
                        people.EmployeePhoto = string.Empty;
                        people.PhotoLen = 0;
                    }

                    lCount++;
                    int iTmpStep = (int)(((Single)lCount / (Single)lMax) * 100);
                    if (iTmpStep != iStep)
                    {
                        iStep = iTmpStep;
                        _logger.LogInformation($"{name} 进度：{iStep}%  {lMax}/{lCount}");
                    }

                }
                catch (Exception)
                {

                    throw;
                }
            }
            wch.Stop();

            _logger.LogInformation($"{name} 处理 {peoples.Count()} 个 URL地址请求耗时:{wch.ElapsedMilliseconds } ms");

        }

        private static string GetExcelCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Unknown:
                    return cell.StringCellValue;
                case CellType.Numeric:
                    if (cell.ToString().Length > 15)
                    {
                        return cell.ToString();
                    }
                    return cell.NumericCellValue.ToString();
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Formula:
                    return "=" + cell.CellFormula;
                case CellType.Blank:
                    return string.Empty;
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                default:
                    return cell.StringCellValue;
            }
        }

        /// <summary>
        /// 清空所有人员
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("ClearPeople")]
        public IActionResult ClearPeople()
        {
            _PeopleDB.ClearPeople();
            return new JsonResult(new JsonResultModel());
        }
    }
}
